const { DataTypes } = require('sequelize')
const sequelize = require('../config/database')

const UserLog = sequelize.define('UserLog', {
  id: {
    type: DataTypes.INTEGER,
    primaryKey: true,
    autoIncrement: true,
    comment: '日志ID'
  },
  user_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '用户ID'
  },
  type: {
    type: DataTypes.STRING(20),
    allowNull: false,
    comment: '日志类型（status-状态变更/department-部门调动/merge-用户合并）'
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false,
    comment: '日志内容'
  },
  before: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '变更前的数据（JSON格式）'
  },
  after: {
    type: DataTypes.JSON,
    allowNull: true,
    comment: '变更后的数据（JSON格式）'
  },
  operator_id: {
    type: DataTypes.INTEGER,
    allowNull: false,
    comment: '操作人ID'
  },
  ip: {
    type: DataTypes.STRING(50),
    allowNull: true,
    comment: '操作IP'
  },
  remark: {
    type: DataTypes.STRING(200),
    allowNull: true,
    comment: '备注说明'
  }
}, {
  tableName: 'user_logs',
  timestamps: true,
  indexes: [
    {
      fields: ['user_id'],
      name: 'user_logs_user_id_index'
    },
    {
      fields: ['type'],
      name: 'user_logs_type_index'
    },
    {
      fields: ['created_at'],
      name: 'user_logs_created_at_index'
    }
  ]
})

// 与用户的关联关系
const User = require('./user')

UserLog.belongsTo(User, {
  foreignKey: 'user_id',
  as: 'user'
})

UserLog.belongsTo(User, {
  foreignKey: 'operator_id',
  as: 'operator'
})

module.exports = UserLog 